# Universidade Federal do Ceará
# Programa de Pós-Graduação em Engenharia de Transportes
# Modalgem da Demanda por Transportes
# Modelo de Producao de Viagens - Regressão Linear
# Caio Gustavo, Nelson Quesado e Paulo Bruno

# Limpeza de Environment
rm(list = ls());gc()
##          used (Mb) gc trigger (Mb) limit (Mb) max used (Mb)
## Ncells 464539 24.9     993808 53.1         NA   666891 35.7
## Vcells 882883  6.8    8388608 64.0      16384  1826456 14.0
# Bibliotecas utilizadas
library(tidyverse)
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.1 ──
## ✓ ggplot2 3.3.5     ✓ purrr   0.3.4
## ✓ tibble  3.1.2     ✓ dplyr   1.0.6
## ✓ tidyr   1.1.3     ✓ stringr 1.4.0
## ✓ readr   1.4.0     ✓ forcats 0.5.1
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## x dplyr::filter() masks stats::filter()
## x dplyr::lag()    masks stats::lag()
library(readxl)
library(sjPlot)
## Registered S3 methods overwritten by 'parameters':
##   method                           from      
##   as.double.parameters_kurtosis    datawizard
##   as.double.parameters_skewness    datawizard
##   as.double.parameters_smoothness  datawizard
##   as.numeric.parameters_kurtosis   datawizard
##   as.numeric.parameters_skewness   datawizard
##   as.numeric.parameters_smoothness datawizard
##   print.parameters_distribution    datawizard
##   print.parameters_kurtosis        datawizard
##   print.parameters_skewness        datawizard
##   summary.parameters_kurtosis      datawizard
##   summary.parameters_skewness      datawizard
## #refugeeswelcome
library(lmtest)
## Loading required package: zoo
## 
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
library(car)
## Loading required package: carData
## 
## Attaching package: 'car'
## The following object is masked from 'package:dplyr':
## 
##     recode
## The following object is masked from 'package:purrr':
## 
##     some
library(rgdal)
## Loading required package: sp
## Please note that rgdal will be retired by the end of 2023,
## plan transition to sf/stars/terra functions using GDAL and PROJ
## at your earliest convenience.
## 
## rgdal: version: 1.5-27, (SVN revision 1148)
## Geospatial Data Abstraction Library extensions to R successfully loaded
## Loaded GDAL runtime: GDAL 3.2.1, released 2020/12/29
## Path to GDAL shared files: /Library/Frameworks/R.framework/Versions/4.1/Resources/library/rgdal/gdal
## GDAL binary built with GEOS: TRUE 
## Loaded PROJ runtime: Rel. 7.2.1, January 1st, 2021, [PJ_VERSION: 721]
## Path to PROJ shared files: /Library/Frameworks/R.framework/Versions/4.1/Resources/library/rgdal/proj
## PROJ CDN enabled: FALSE
## Linking to sp version:1.4-5
## To mute warnings of possible GDAL/OSR exportToProj4() degradation,
## use options("rgdal_show_exportToProj4_warnings"="none") before loading sp or rgdal.
## Overwritten PROJ_LIB was /Library/Frameworks/R.framework/Versions/4.1/Resources/library/rgdal/proj
library(ape)
library(spgwr)
## Loading required package: spData
## To access larger datasets in this package, install the spDataLarge
## package with: `install.packages('spDataLarge',
## repos='https://nowosad.github.io/drat/', type='source')`
## NOTE: This package does not constitute approval of GWR
## as a method of spatial analysis; see example(gwr)
library(sf)
## Linking to GEOS 3.8.1, GDAL 3.2.1, PROJ 7.2.1
library(spdep)
## Registered S3 method overwritten by 'spdep':
##   method   from
##   plot.mst ape
library(spatialreg)
## Loading required package: Matrix
## 
## Attaching package: 'Matrix'
## The following objects are masked from 'package:tidyr':
## 
##     expand, pack, unpack
## 
## Attaching package: 'spatialreg'
## The following objects are masked from 'package:spdep':
## 
##     as_dgRMatrix_listw, as_dsCMatrix_I, as_dsCMatrix_IrW,
##     as_dsTMatrix_listw, as.spam.listw, can.be.simmed, cheb_setup,
##     create_WX, do_ldet, eigen_pre_setup, eigen_setup, eigenw,
##     errorsarlm, get.ClusterOption, get.coresOption, get.mcOption,
##     get.VerboseOption, get.ZeroPolicyOption, GMargminImage, GMerrorsar,
##     griffith_sone, gstsls, Hausman.test, impacts, intImpacts,
##     Jacobian_W, jacobianSetup, l_max, lagmess, lagsarlm, lextrB,
##     lextrS, lextrW, lmSLX, LU_prepermutate_setup, LU_setup,
##     Matrix_J_setup, Matrix_setup, mcdet_setup, MCMCsamp, ME, mom_calc,
##     mom_calc_int2, moments_setup, powerWeights, sacsarlm,
##     SE_classic_setup, SE_interp_setup, SE_whichMin_setup,
##     set.ClusterOption, set.coresOption, set.mcOption,
##     set.VerboseOption, set.ZeroPolicyOption, similar.listw, spam_setup,
##     spam_update_setup, SpatialFiltering, spautolm, spBreg_err,
##     spBreg_lag, spBreg_sac, stsls, subgraph_eigenw, trW
library(spgwr)
library(leaflet)
library(broom)

# Definicao do diretorio de trabalho
setwd("~/OneDrive/UFC - Doutorado/2021.2/Modelagem da Demanda por Transportes/Entregas/02 - Producao de Viagens Regressao Linear/dados")

# Carregamento dos Dados OD Domiciliar
# Dados de viagem, filtrando base domiciliar e motivo trabalho
viagens <- read_excel("Banco OD Domiciliar - Versao Final.xlsx", sheet = "VIAGENS")
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in G3476 / R3476C7: got '8:40'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in G3477 / R3477C7: got '7:10'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in G3478 / R3478C7: got '18:00'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in I3478 / R3478C9: got '18:40'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in G3570 / R3570C7: got '10:30'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in I3570 / R3570C9: got '10:50'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in G3741 / R3741C7: got '12:10'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in I3741 / R3741C9: got '13:20'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in G3743 / R3743C7: got '10:20'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in I3743 / R3743C9: got '10:50'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in G3745 / R3745C7: got '11:40'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in I3745 / R3745C9: got '12:40'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in G3747 / R3747C7: got '17:20'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in I3747 / R3747C9: got '17:50'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in G4353 / R4353C7: got '13:00'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in I4353 / R4353C9: got '14:30'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in G4355 / R4355C7: got '11:40'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in I4355 / R4355C9: got '13:00'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in G4356 / R4356C7: got '22:00'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in I4356 / R4356C9: got '23:30'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in G4432 / R4432C7: got '11:10'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in I4432 / R4432C9: got '11:30'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in G4435 / R4435C7: got '11:10'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in I4435 / R4435C9: got '11:30'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in G4436 / R4436C7: got '11:50'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in I4436 / R4436C9: got '12:00'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in G4437 / R4437C7: got '18:00'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in I4437 / R4437C9: got '18:20'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in G6596 / R6596C7: got '12:00'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in I6596 / R6596C9: got '12:10'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in G6598 / R6598C7: got '12:00'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in I6598 / R6598C9: got '12:10'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in G6600 / R6600C7: got '12:00'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in I6600 / R6600C9: got '12:10'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in G9870 / R9870C7: got '11:30'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in I9870 / R9870C9: got '12:00'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in G9899 / R9899C7: got '5:00'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in G9900 / R9900C7: got '19:00'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in I9900 / R9900C9: got '19:40'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in G9902 / R9902C7: got '18:30'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in I9902 / R9902C9: got '19:00'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in G9904 / R9904C7: got '17:30'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in I9904 / R9904C9: got '18:00'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in G14812 / R14812C7: got '7:30'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in G14814 / R14814C7: got '10:30'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in I14814 / R14814C9: got '11:00'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in G14816 / R14816C7: got '6:40'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in G14921 / R14921C7: got '9:00'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in G14923 / R14923C7: got '10:40'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in I14923 / R14923C9: got '11:00'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in G14929 / R14929C7: got '9:00'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in G14931 / R14931C7: got '10:40'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in I14931 / R14931C9: got '11:00'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in G18851 / R18851C7: got '6:30'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in G19430 / R19430C7: got '11:40'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in I19430 / R19430C9: got '12:40'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in G19432 / R19432C7: got '12:20'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in I19432 / R19432C9: got '12:40'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in G19760 / R19760C7: got '8:00'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in G20144 / R20144C7: got '9:00'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in G20148 / R20148C7: got '10:30'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in I20148 / R20148C9: got '11:10'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in G20150 / R20150C7: got '9:00'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in G20152 / R20152C7: got '8:30'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in G20154 / R20154C7: got '13:00'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in I20154 / R20154C9: got '13:10'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in G23370 / R23370C7: got '7:00'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in G23372 / R23372C7: got '7:00'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in G23377 / R23377C7: got '11:50'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in I23377 / R23377C9: got '12:00'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in G23392 / R23392C7: got '7:00'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in G23393 / R23393C7: got '7:00'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in G64888 / R64888C7: got '7:30'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in G71081 / R71081C7: got '11:00'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in I71081 / R71081C9: got '11:30'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in G82543 / R82543C7: got '18:00'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in I82543 / R82543C9: got '19:10'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in G82544 / R82544C7: got '6:00'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in G82563 / R82563C7: got '6:30'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in G82564 / R82564C7: got '17:00'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in I82564 / R82564C9: got '18:00'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in G82565 / R82565C7: got '7:40'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in G82566 / R82566C7: got '16:40'
## Warning in read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :
## Expecting numeric in I82566 / R82566C9: got '17:00'
dados_viagens <- viagens %>%
  filter(`Motivo Origem` == "Trabalho" & `Motivo Destino` == "Residência" | `Motivo Origem` == "Residência" & `Motivo Destino` == "Trabalho") %>%
  group_by(`Identificador Domicílio`) %>%
  summarise(n()) %>%
  setNames(c("domicilio", "viagens.obs"))

domicilios <- read_xlsx("Banco OD Domiciliar - Versao Final.xlsx", sheet = "DOMICILIOS")
## New names:
## * `` -> ...14
## * `` -> ...15
dados_domicilios <- domicilios %>% filter(Município == "Fortaleza") %>%
  mutate(veic = Automóveis + Motocicletas + Bicicletas) %>%
  select(`Identificador Domicílio`, `Zona Domicílio`, veic, `Moradores Domicílio`, `Latitude Setor Censitário`, `Longitude Setor Censitário`, `Fator Domicílio`) %>%
  setNames(c("domicilio", "zona", "veiculos", "moradores", "lat", "long", "ft.exp.dom"))

acess <- read_csv("zonas_var_clusterizacao_v2.csv") %>% 
  select(ZONA_NOVA, tempo) %>%
  setNames(c("zona", "tempo"))
## 
## ── Column specification ────────────────────────────────────────────────────────
## cols(
##   ZONA_NOVA = col_double(),
##   ID = col_double(),
##   AREA = col_double(),
##   BAIRRO_MUN = col_character(),
##   MUNICPIO = col_character(),
##   long = col_double(),
##   lat = col_double(),
##   tempo = col_double(),
##   dens_pop = col_double(),
##   temponorm = col_double(),
##   dens_popnorm = col_double(),
##   cluster = col_double()
## )
# juntando os dados
dados <- dados_domicilios %>% left_join(dados_viagens, by = "domicilio")
dados$viagens.obs[is.na(dados$viagens.obs)] <- 0

# Tirando o que nao vai ajudar a explicar a produção
getmode <- function(v) { # funcao de estimar moda
  uniqv <- unique(v)
  uniqv[which.max(tabulate(match(v, uniqv)))]
}

dad.agr <- dados %>%
  select(-domicilio) %>%
    group_by(zona) %>%
  summarise(
    veiculos = sum(veiculos*ft.exp.dom/sum(ft.exp.dom)),
    moradores = sum(moradores*ft.exp.dom/sum(ft.exp.dom)),
    viagens =sum(viagens.obs*ft.exp.dom/sum(ft.exp.dom)),
    lat = getmode(lat), long = getmode(long)) %>%
  left_join(acess, by = "zona")

dad.agr$tempo[is.na(dad.agr$tempo)] <- mean(dad.agr$tempo, na.rm = TRUE)
remove(getmode, dados, domicilios, viagens)

# Remocao do outlier
dad.agr <- dad.agr[-253,] # nesta amostra, o outlier é a zona 253

# passo 1/4 estimativa do kernel
gwr_kernel <- gwr.sel(
  formula = viagens ~ veiculos + moradores + tempo,
  data = dad.agr,
  coords = cbind(dad.agr$long, dad.agr$lat),
  adapt = TRUE
)
## Adaptive q: 0.381966 CV score: 27.82596 
## Adaptive q: 0.618034 CV score: 27.69676 
## Adaptive q: 0.763932 CV score: 27.67442 
## Adaptive q: 0.7651676 CV score: 27.67396 
## Adaptive q: 0.8548656 CV score: 27.66899 
## Adaptive q: 0.8180433 CV score: 27.6692 
## Adaptive q: 0.8395226 CV score: 27.66916 
## Adaptive q: 0.910302 CV score: 27.66427 
## Adaptive q: 0.9445636 CV score: 27.66569 
## Adaptive q: 0.9127381 CV score: 27.66455 
## Adaptive q: 0.8891272 CV score: 27.66653 
## Adaptive q: 0.9022139 CV score: 27.66469 
## Adaptive q: 0.9079025 CV score: 27.66437 
## Adaptive q: 0.9097193 CV score: 27.66421 
## Adaptive q: 0.9093324 CV score: 27.66419 
## Adaptive q: 0.9092303 CV score: 27.6642 
## Adaptive q: 0.909462 CV score: 27.66418 
## Adaptive q: 0.9095603 CV score: 27.66419 
## Adaptive q: 0.9094213 CV score: 27.66418 
## Adaptive q: 0.9095027 CV score: 27.66418 
## Adaptive q: 0.909462 CV score: 27.66418
# passo 2/4 computo do modelo
mod.gwr <- gwr(
  formula = viagens ~ veiculos + moradores + tempo,
  data = dad.agr,
  coords = cbind(dad.agr$long, dad.agr$lat),
  adapt = gwr_kernel,
  hatmatrix = TRUE,
  se.fit = TRUE
)

remove(acess, dados_domicilios, dados_viagens, gwr_kernel)

# passo 3/4 exportacao dos resultaods
pro.via.gwr <- cbind(dad.agr, as.matrix(as.data.frame(mod.gwr$SDF)))
pro.via.gwr <- data.frame(pro.via.gwr, .name_repair = "minimal")

# Carregando o Shape
shape <- readOGR("zoneamento", stringsAsFactors = FALSE)
## Warning in readOGR("zoneamento", stringsAsFactors = FALSE): First layer Zoneamento read; multiple layers present in
## /Users/Nelson/OneDrive/UFC - Doutorado/2021.2/Modelagem da Demanda por Transportes/Entregas/02 - Producao de Viagens Regressao Linear/dados/zoneamento, check layers with ogrListLayers()
## OGR data source with driver: ESRI Shapefile 
## Source: "/Users/Nelson/OneDrive/UFC - Doutorado/2021.2/Modelagem da Demanda por Transportes/Entregas/02 - Producao de Viagens Regressao Linear/dados/zoneamento", layer: "Zoneamento"
## with 325 features
## It has 5 fields
## Integer64 fields read as strings:  ID
class(shape)
## [1] "SpatialPolygonsDataFrame"
## attr(,"package")
## [1] "sp"
# Juntando chape com amostra+modelo
dad.geo <- merge(shape, pro.via.gwr, by.x = "ZONA_NOVA", by.y = "zona")
proj4string(dad.geo) <- CRS("+proj=longlat +datum=WGS84 +no_defs") # passar as coordenadas de latitude e longitude para o objeto
remove(dad.agr, mod.gwr, pro.via.gwr, shape)

pal <- colorBin("Spectral", domain = NULL, n = 5)

# producao media de viagens
leaflet(data = dad.geo) %>%
  addProviderTiles("CartoDB.Positron") %>%
  addPolygons(fillColor = ~pal(dad.geo$viagens), 
              fillOpacity = 0.8, 
              color = "#BDBDC3", 
              weight = 1,
              popup = paste("Viagens/Domicílio:", round(dad.geo$veiculos.1, 2))) %>%
  addLegend("bottomright", pal = pal, values = ~dad.geo$veiculos.1,
            title = "Distribuição Espacial da Produção Média de Viagens")
# producao media estimada de viagens
leaflet(data = dad.geo) %>%
  addProviderTiles("CartoDB.Positron") %>%
  addPolygons(fillColor = ~pal(dad.geo$pred), 
              fillOpacity = 0.8, 
              color = "#BDBDC3", 
              weight = 1,
              popup = paste("Viagens/Domicílio:", round(dad.geo$veiculos.1, 2))) %>%
  addLegend("bottomright", pal = pal, values = ~dad.geo$veiculos.1,
            title = "Distribuição Espacial da Produção Média de Viagens ESTIMADA")
# R2
leaflet(data = dad.geo) %>%
  addProviderTiles("CartoDB.Positron") %>%
  addPolygons(fillColor = ~pal(dad.geo$localR2), 
              fillOpacity = 0.8, 
              color = "#BDBDC3", 
              weight = 1,
              popup = paste("R2:", round(dad.geo$veiculos.1, 2))) %>%
  addLegend("bottomright", pal = pal, values = ~dad.geo$veiculos.1,
            title = "Distribuição Espacial do R2")
# residuos
leaflet(data = dad.geo) %>%
  addProviderTiles("CartoDB.Positron") %>%
  addPolygons(fillColor = ~pal(dad.geo$veiculos.1), 
              fillOpacity = 0.8, 
              color = "#BDBDC3", 
              weight = 1,
              popup = paste("Resíduo:", round(dad.geo$veiculos.1, 2))) %>%
  addLegend("bottomright", pal = pal, values = ~dad.geo$veiculos.1,
            title = "Distribuição Espacial dos Resíduos")
# ß0 intercept
leaflet(data = dad.geo) %>%
  addProviderTiles("CartoDB.Positron") %>%
  addPolygons(fillColor = ~pal(dad.geo$X.Intercept.), 
              fillOpacity = 0.8, 
              color = "#BDBDC3", 
              weight = 1,
              popup = paste("ß0:", round(dad.geo$veiculos.1, 2))) %>%
  addLegend("bottomright", pal = pal, values = ~dad.geo$veiculos.1,
            title = "Distribuição Espacial do Intercepto")
# ß veiculos
leaflet(data = dad.geo) %>%
  addProviderTiles("CartoDB.Positron") %>%
  addPolygons(fillColor = ~pal(dad.geo$veiculos.1), 
              fillOpacity = 0.8, 
              color = "#BDBDC3", 
              weight = 1,
              popup = paste("ß veiculo/dom:", round(dad.geo$veiculos.1, 2))) %>%
  addLegend("bottomright", pal = pal, values = ~dad.geo$veiculos.1,
            title = "Distribuição Espacial do ß veiculo/dom")
# ß moradores
leaflet(data = dad.geo) %>%
  addProviderTiles("CartoDB.Positron") %>%
  addPolygons(fillColor = ~pal(dad.geo$moradores.1), 
              fillOpacity = 0.8, 
              color = "#BDBDC3", 
              weight = 1,
              popup = paste("ß moradores/dom:", round(dad.geo$veiculos.1, 2))) %>%
  addLegend("bottomright", pal = pal, values = ~dad.geo$veiculos.1,
            title = "Distribuição Espacial do ß moradores/dom")
# ß tempo (acessibilidade)
leaflet(data = dad.geo) %>%
  addProviderTiles("CartoDB.Positron") %>%
  addPolygons(fillColor = ~pal(dad.geo$tempo.1), 
              fillOpacity = 0.8, 
              color = "#BDBDC3", 
              weight = 1,
              popup = paste("ß desacessibilidade:", round(dad.geo$veiculos.1, 2))) %>%
  addLegend("bottomright", pal = pal, values = ~dad.geo$veiculos.1,
            title = "Distribuição Espacial do ß desacessibilidade")